package com.lrz.util;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lrz.common.IdWorker;
import com.lrz.common.Result;
import com.lrz.common.StatusCode;
import io.minio.*;
import io.minio.messages.Bucket;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class MinIOUtil {

    @Value("${minio.bucketName}")
    private String bucketName;

    @Resource
    private MinioClient minioClient;

    @Resource
    private IdWorker idWorker;

    /**
     * 查看存储bucket是否存在
     *
     * @return boolean
     */
    public Boolean bucketExists(String bucketName) {
        Boolean found;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return found;
    }

    /**
     * 获取全部bucket
     */
    public List<Bucket> getAllBuckets() {
        try {
            List<Bucket> buckets = minioClient.listBuckets();
            return buckets;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public Result upload(MultipartFile file) {
//        if (file == null || file.length == 0) {
//            return new Result(false, StatusCode.ERROR, "上传文件不能为空");
//        }
//        List<String> orgfileNameList = new ArrayList<>(file.length);

//        for (MultipartFile multipartFile : file) {
        String orgfileName = file.getOriginalFilename();
        String substring = orgfileName.substring(orgfileName.indexOf("."), orgfileName.length());
        String fileName = idWorker.nextId() + substring;
//        System.out.println(file.getSize());
//        System.out.println(file.getContentType());
//            orgfileNameList.add(orgfileName);
        try {//文件上传
            InputStream in = file.getInputStream();
            ObjectWriteResponse objectWriteResponse = minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(in, file.getSize(), -1).contentType(file.getContentType()).build());
            System.out.println(objectWriteResponse.toString());
            in.close();
        } catch (Exception e) {
            log.error(e.getMessage());
            return new Result(false, StatusCode.ERROR, "上传失败");
        }
//        }
        Map<String, String> data = new HashMap<String, String>();
        data.put("bucketName", bucketName);
        data.put("fileName", file.getName());
        String url = "http://124.222.69.186:9000/" + bucketName + "/" + fileName;
        data.put("url", url);
        return new Result(true, StatusCode.OK, "上传成功", data);
    }


    public void download(HttpServletResponse response, String fileName) {
        InputStream in = null;
        try {// 获取对象信息
            StatObjectResponse stat = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(fileName).build());
            response.setContentType(stat.contentType());
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); //文件下载
            in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
            IOUtils.copy(in, response.getOutputStream());
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }
    }
}

